/**
 * Created by dio on 2017/2/21 0021.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {Image, ListView, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import CommonRenderer from "../CommonRenderer";
import CustomStyle from "../../../../common/style/CustomStyle";
import SectionTitle from "./SectionTitle";
import * as Url from "../../../constant/Url";
import {request} from "../../../../common/util/RequestUtil";
import * as BuyCarAction from "../../../redux/action/BuyCar";
import {refreshBuyCarFilter} from "../../../page/buyCar/BuyCar";
import {connect} from "react-redux";
import {goToPage} from "../../../main/MainUI";
import {Actions} from "react-native-router-flux";

const DATA_SOURCE = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

class HomePageCarList extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isRefreshing: false,
            shopList: [],
        };
        this._updateBuyCarFilter = this._updateBuyCarFilter.bind(this);
        this._goToPage = this._goToPage.bind(this);
        this.renderHeader = this.renderHeader.bind(this);
        this._fetchShop = this._fetchShop.bind(this);
    }

    static propTypes = {
        searchText: '',
    };

    componentDidMount() {
        this._fetchShop();
    }

    componentWillUnmount() {
    }

    render() {
        return (
            <ListView
                initialListSize={5}
                dataSource={DATA_SOURCE.cloneWithRows(this.props.carList)}
                renderRow={this.renderRow.bind(this)}
                enableEmptySections={true}
                refreshable={false} // enable pull-to-refresh for iOS and touch-to-refresh for Android
                renderHeader={this.renderHeader}
                renderFooter={this.renderLookMoreCars}
                withSections={false} // enable sections
                renderSeparator={this.renderSeparator}
            />
        );
    }

    renderLookMoreCars() {
        return (
            <TouchableOpacity onPress={() => {
                goToPage(1);
            }}
                              style={{
                                  backgroundColor: '#ffffff',
                                  height: CustomStyle.getActualSizeInVertical(160),
                                  justifyContent: 'center',
                                  alignItems: 'center',
                              }}>
                <View style={{
                    width: CustomStyle.getActualSizeInHorizontal(460),
                    height: CustomStyle.getActualSizeInVertical(68),
                    borderRadius: CustomStyle.getActualSizeInHorizontal(4),
                    borderColor: "#ffc000",
                    borderWidth: CustomStyle.getActualSizeInVertical(1),
                    justifyContent: 'center',
                    alignItems: 'center',
                }}>
                    <Text style={[CustomStyle.baseText, {
                        color: '#ffc000',
                        fontSize: CustomStyle.getActualFontSize(30),
                    }]}>查看更多车辆</Text>
                </View>
            </TouchableOpacity>
        );
    }

    renderSeparator() {
        return <View style={CustomStyle.separator}/>
    }

    renderRow(rowData) {
        return <CommonRenderer rowData={rowData}/>;
    }


    renderHeader() {
        const hotCarList = [];
        hotCarList.push(new HotCarBean("奔驰", require('../../../../img/car_benchi.png')));
        hotCarList.push(new HotCarBean("本田", require('../../../../img/car_bentian.png')));
        hotCarList.push(new HotCarBean("丰田", require('../../../../img/car_fengtian.png')));
        hotCarList.push(new HotCarBean("奥迪", require('../../../../img/car_aodi.png')));
        hotCarList.push(new HotCarBean("标致", require('../../../../img/car_biaozhi.png')));
        hotCarList.push(new HotCarBean("宝马", require('../../../../img/car_baoma.png')));

        const priceList = [];
        priceList.push({show: '5万以下', filter: {from: 0, to: 5}});
        priceList.push({show: '5-10万', filter: {from: 5, to: 10,}});
        priceList.push({show: '10-15万', filter: {from: 10, to: 15}});
        priceList.push({show: '15-20万', filter: {from: 15, to: 20}});
        priceList.push({show: '20-30万', filter: {from: 20, to: 30}});
        priceList.push({show: '30-50万', filter: {from: 30, to: 50}});

        const handleList = [];
        handleList.push(<HandleCard imageStyle={styles.handleImage} textStyle={styles.handleText}
                                    image={require('../../../../img/homepage/buyCar.png')} text={'买车'} click={() => {
            this._goToPage(1);
        }}/>);
        handleList.push(<HandleCard imageStyle={styles.handleImage} textStyle={styles.handleText}
                                    image={require('../../../../img/homepage/soldCar.png')} text={'卖车'} click={() => {
            this._goToPage(2);
        }}/>);
        /*    handleList.push(<HandleCard imageStyle={styles.handleImage} textStyle={styles.handleText}
                                    image={require('../../../../img/homepage/auction.png')} text={'竞拍'} click={() => {
            Actions.CarsForAuctionUI();
         }}/>);*/
        handleList.push(<HandleCard imageStyle={styles.handleImage} textStyle={styles.handleText}
                                    image={require('../../../../img/homepage/accredit.png')} text={'质保'} click={() => {
            Actions.Accredit();
        }}/>);
        handleList.push(<HandleCard imageStyle={styles.handleImage} textStyle={styles.handleText}
                                    image={require('../../../../img/homepage/helpLook.png')} text={'帮看'} click={() => {
            Actions.HelpLook();
        }}/>);

        return (
            <View style={{
                width: CustomStyle.screenWidth,
            }}>

                {/*操作列表*/}
                <View style={{
                    flexDirection: 'row',
                    height: CustomStyle.getActualSizeInVertical(240),
                }}>
                    {handleList}
                </View>

                {this._renderDivider()}

                {/*价格选择*/}
                <View style={styles.priceList}>{
                    priceList.slice(0, 3).map((item) => <Price text={item.show} onClick={() => {
                        this._updateBuyCarFilter({price: item.filter});
                    }}/>)
                }</View>
                <View style={styles.priceList}>{
                    priceList.slice(3).map((item) => <Price text={item.show} onClick={() => {
                        this._updateBuyCarFilter({price: item.filter});
                    }}/>)
                }</View>

                {/*热门车辆选择*/}
                <View style={styles.priceList}>{
                    hotCarList.slice(0, 3).map((hotCarBean) => <HotCard text={hotCarBean.text}
                                                                        image={hotCarBean.image}
                                                                        onClick={() => {
                                                                            this._updateBuyCarFilter({
                                                                                brand: hotCarBean.text,
                                                                                series: ''
                                                                            })
                                                                        }}
                    />)
                }</View>
                <View style={styles.priceList}>{
                    hotCarList.slice(3).map((hotCarBean) => <HotCard text={hotCarBean.text}
                                                                     image={hotCarBean.image}
                                                                     onClick={() => {
                                                                         this._updateBuyCarFilter({
                                                                             brand: hotCarBean.text,
                                                                             series: ''
                                                                         })
                                                                     }}
                    />)
                }</View>

                <View style={{
                    height: CustomStyle.getActualSizeInVertical(2),
                    backgroundColor: 'rgba(0, 0, 0, 0.1)',
                    marginTop: CustomStyle.getActualSizeInVertical(30),
                }}/>
                <TouchableOpacity
                    style={{
                        height: CustomStyle.getActualSizeInVertical(78),
                        justifyContent: 'center',
                        alignItems: 'center',
                    }}
                    onPress={() => {
                        goToPage(1);
                        Actions.BrandRoot({
                            onSelected: (brand, series) => {
                                this._updateBuyCarFilter({
                                    brand,
                                    series,
                                })
                            }
                        });
                    }}
                >
                    <View
                        style={{
                            flexDirection: 'row',
                            alignItems: 'center',
                        }}>
                        <Image style={{
                            width: CustomStyle.getActualSizeInHorizontal(30),
                            height: CustomStyle.getActualSizeInVertical(20),
                        }} source={require('../../../../img/car_all.png')}/>
                        <Text style={[CustomStyle.baseText, {
                            color: '#857e6e', fontSize: CustomStyle.getActualSizeInHorizontal(28),
                            marginLeft: CustomStyle.getActualSizeInHorizontal(20),
                        }]}>全部品牌</Text>
                    </View>
                </TouchableOpacity>
                {this._renderDivider()}
                {this._renderHotShop()}
                {this._renderDivider()}
                <SectionTitle title='热门车辆'/>
            </View>
        );
    }

    _updateBuyCarFilter(param) {
        this.props.updateFilter(param);
        this._goToPage(1);
        refreshBuyCarFilter();
    }

    _goToPage(index) {
        goToPage(index);
    }

    _renderDivider() {
        return <View style={{height: CustomStyle.getActualSizeInVertical(20), backgroundColor: '#f9f9f9'}}/>;
    }

    _renderHotShop() {
        if (this.state.shopList.length) {
            return <View >
                <SectionTitle title='热门店铺' showArrow={true} rightText={'查看更多'} rightClick={() => {
                    Actions.ShopSearch();
                }}/>
                <View style={{height: CustomStyle.getActualSizeInVertical(280), flexDirection: 'row'}}>
                    <ListView
                        showsHorizontalScrollIndicator={false}
                        horizontal={true}
                        dataSource={DATA_SOURCE.cloneWithRows(this.state.shopList)}
                        renderRow={(item) => {
                            return <HandleCard style={styles.shopContainer} image={item.logo} text={item.name}
                                               click={() => {
                                                   Actions.ShopDetail({id: item.id})
                                               }}
                                               imageStyle={styles.shopImage}
                                               textStyle={styles.shopText}/>
                        }}/>
                </View>
            </View>
        }
    }

    _fetchShop() {
        let url = Url.BASE_URL + '/shop/get_shops_by_max';
        const param = new FormData();
        param.append('max', 10);
        request(url, 'post', param).then(json => {
            const data = json.data;
            const imagePrefix = data.imgPrefix;
            const list = data.list;
            const shopList = list.map(item => {
                let image = !item.logo ? require('../../../../img/homepage/defaultShop.png') : {uri: imagePrefix + item.logo};
                return Object.assign({}, item, {logo: image});
            });
            console.log('searchShop  ' + JSON.stringify(json));
            this.setState({shopList});
        }).catch(err => {
            this.setState({shopList: []});
        });
    }

}

class Price extends Component {
    static propTypes = {
        text: PropTypes.string,
        onClick: PropTypes.func,
    };
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {};
    }

    render() {
        return (
            <TouchableOpacity
                onPress={this.props.onClick}
                style={{flex: 1, alignItems: 'center', justifyContent: 'center',}}>
                <Text
                    style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(30),
                        color: '#555555',
                    }]}>{this.props.text}</Text>
            </TouchableOpacity>
        );
    }
}

class HotCard extends Component {
    static propTypes = {
        text: PropTypes.string,
        image: PropTypes.any,
        onClick: PropTypes.func,
        hotCarBean: PropTypes.object,
    };
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {};
    }

    render() {
        return (
            <TouchableOpacity
                onPress={this.props.onClick}
                style={{flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row',}}>
                <Image
                    resizeMode='contain'
                    style={{
                        width: CustomStyle.getActualSizeInHorizontal(48),
                        height: CustomStyle.getActualSizeInVertical(48),
                    }} source={this.props.image}/>
                <Text
                    style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(30),
                        color: '#555555',
                        marginLeft: CustomStyle.getActualSizeInHorizontal(10),
                    }]}>{this.props.text}</Text>
            </TouchableOpacity>
        );
    }
}

class HandleCard extends Component {
    static propTypes = {
        image: PropTypes.any,
        imageStyle: Image.propTypes.style,
        text: PropTypes.string,
        textStyle: Text.propTypes.style,
        click: PropTypes.func,
    };

    render() {
        return (
            <TouchableOpacity
                onPress={() => {
                    this.props.click();
                }}
                style={[{alignItems: 'center', justifyContent: 'center', flex: 1}, this.props.style,]}>
                <Image source={this.props.image}
                       resizeMode={'contain'}
                       style={[this.props.imageStyle]}/>
                <Text
                    numberOfLines={1}
                    style={[CustomStyle.baseText, this.props.textStyle]}>{this.props.text}</Text>
            </TouchableOpacity>
        );
    }
}

class HotCarBean {
    constructor(text, image) {
        this.text = text;
        this.image = image;
    }
}


const styles = StyleSheet.create({
    priceList: {
        marginTop: CustomStyle.getActualSizeInVertical(40),
        justifyContent: 'center',
        flex: 1,
        flexDirection: 'row',
    },
    handleContainer: {},
    handleImage: {
        height: CustomStyle.getActualSizeInVertical(100),
        width: CustomStyle.getActualSizeInHorizontal(100),
    },
    handleText: {
        fontSize: CustomStyle.getActualFontSize(24),
        color: '#4a3d18',
        marginTop: CustomStyle.getActualSizeInVertical(20),
    },
    shopContainer: {
        width: CustomStyle.getActualSizeInHorizontal(165),
    },
    shopImage: {
        height: CustomStyle.getActualSizeInVertical(120),
        width: CustomStyle.getActualSizeInHorizontal(120),
    },
    shopText: {
        fontSize: CustomStyle.getActualFontSize(24),
        color: '#4a3d18',
        marginTop: CustomStyle.getActualSizeInVertical(20),
        marginLeft: CustomStyle.getActualSizeInHorizontal(8),
        marginRight: CustomStyle.getActualSizeInHorizontal(8),
    },

});

const mapStateToProps = (state) => {
    const {areaList, hotCarList} = state;
    return {
        areaList: areaList.data,
        carList: hotCarList.data,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        updateFilter: param => dispatch(BuyCarAction.buyCarFilter(param)),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(HomePageCarList);
